package com.liuh.fram.err;

import com.jfinal.kit.PropKit;
import com.liuh.fram.log.Log4jLogExtra;

/**
 * @note 业务异常定义
 * @author liuh
 * */
public class LocalException extends RuntimeException {

	Log4jLogExtra log4jExtra = new Log4jLogExtra(LocalException.class);

	private static final long serialVersionUID = 1L;

	// 默认异常类型
	private ErrorType errorType = ErrorType.defaultErr;
	// 错误消息中动态参数
	private String errParam;
	// 根据接口响应生成错误模型
	private Error errorM;
	// 异常渲染输出类型
	private ErrorRenderType errRenderType = getErrRender(PropKit
			.get("default_errRender"));

	public LocalException(ErrorType errorType, String errParam) {
		super();
		this.errorType = errorType;
		this.errParam = errParam;
	}

	public LocalException(ErrorType errorType) {
		super();
		this.errorType = errorType;
	}

	public LocalException(Error errorM) {
		super();
		this.errorM = errorM;
	}

	public LocalException(String errMsg) {
		super();
		this.errorM = new Error(errMsg, ErrorType.defaultErr.getCode());
	}

	public Error getErrorM() {
		return errorM;
	}

	public ErrorType getErrorType() {
		return errorType;
	}

	public String getErrParam() {
		return errParam;
	}

	public ErrorRenderType getErrRenderType() {
		return errRenderType;
	}

	public void setErrRenderType(ErrorRenderType errRenderType) {
		this.errRenderType = errRenderType;
	}

	private ErrorRenderType getErrRender(String errRenderMsg) {
		return Enum.valueOf(ErrorRenderType.class, errRenderMsg);
	}

	// 异常输出渲染类型
	public enum ErrorRenderType {
		PC_view500, MB_view500, Compress, NoCompress;
	}

	// 异常枚举类型
	public enum ErrorType {
		sendEmptData("1000"), emptyData("1001"), defaultErr("1002"), noAction(
				"1003"), apiErr("1004"), parseErr("1005"), apiNoAuth("1006"), httpErr(
				"1007");
		// 成员变量
		private String code;

		// 构造方法
		private ErrorType(String code) {
			this.code = code;
		}

		public String getCode() {
			return this.code;
		}
	}

	/**
	 * @note 根据错误状态码转换成错误实体
	 * @author liuh
	 * */
	public Error buildErrorM() {
		ErrorType errorType = this.errorType;
		Error errorM = new Error();
		errorM.setCode(errorType.getCode());
		switch (errorType) {
		case sendEmptData:
			errorM.setMsg("请求的数据为空，请检测确认！");
			break;
		case emptyData:
			errorM.setMsg("响应的数据为空，请检测确认！");
			break;
		case noAction:
			errorM.setMsg("action匹配失败！");
			break;
		case apiErr:
			errorM.setMsg("调用接口异常！【" + errParam + "】");
			break;
		case parseErr:
			errorM.setMsg("数据解析异常！");
			break;
		case apiNoAuth:
			errorM.setMsg("无权限访问应用！");
			break;
		case httpErr:
			errorM.setMsg("返回http错误的代码【" + errParam + "】!");
			break;
		default:
			errorM.setMsg("应用系统异常，稍后重试(default)");
			break;
		}
		return errorM;
	}

}
